package com.bryant.bryant_weather.ui.me

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.bryant.bryant_weather.R
import com.bryant.bryant_weather.WeatherApplication
import com.bryant.bryant_weather.base.BaseBindingFragment
import com.bryant.bryant_weather.databinding.FragmentMeBinding
import com.bryant.bryant_weather.storage.TokenPreferences
import com.bryant.bryant_weather.ui.login.LoginActivity
import com.bryant.bryant_weather.utils.RetrofitClient
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Retrofit

class MeFragment :BaseBindingFragment<FragmentMeBinding>() {
    override fun initBinding(inflater: LayoutInflater, parent: ViewGroup?): FragmentMeBinding {
        return FragmentMeBinding.inflate(inflater,parent,false)
    }

    override fun initView() {
        // 退出登录
        // requireContext() 是 Fragment 提供的专门用于获取 Context 的方法
        //它会检查 Fragment 是否已经关联到 Activity，如果没有则抛出异常
        //相比 context 属性，requireContext() 更安全可靠
        binding.btnLogout.setOnClickListener {
            // 清空 token
            TokenPreferences.getInstance( requireContext()).clearToken()
            // 跳转至登录页
            var intent = Intent(requireContext(), LoginActivity::class.java)
            startActivity(intent)
        }

        // 实现点击头像跳转至修改头像页面
        binding.ivAvatar.setOnClickListener {
            var intent = Intent(requireContext(), ChangeAvatarActivity::class.java)
            startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        getUserInfo()
    }

    override fun onResume() {
        super.onResume()
        getUserInfo()
    }


    private fun getUserInfo() {
        lifecycleScope.launch {
            val res = withContext(Dispatchers.IO){
                RetrofitClient.apiService.getUserInfo()
            }
            if (res.code == 10000){
                val userData = res.data

                binding.tvAccount.text = userData?.username
                binding.tvGender.text = userData?.gender
                binding.tvNickname.text = userData?.nick_name
                binding.tvSignature.text = userData?.motto
               Log.d("MeFragment", "用户信息: $userData")
                loadAvatar(userData?.avatar ?: "")
                // 全局存储
                if (userData != null){
                    WeatherApplication.getInstance().initUser(userData)
                }else{
                    Toast.makeText(requireContext(), "获取用户信息失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
    private fun loadAvatar(avatar: String) {
        lifecycleScope.launch {
            Glide.with(this@MeFragment)
                .load(avatar)
                .apply(RequestOptions()
                    .circleCrop() // 圆形显示
                    .placeholder(R.mipmap.avatar2)
                    .error(R.mipmap.avatar2)
                )
                .into(binding.ivAvatar)

        }
    }
}